/*
 * Copyright (c) 2014-2019 2018 xmars All Rights Reserved.
 * ProjectName: xmars
 * FileName: ContextUtil.java
 * Author: pipi
 * Date: 18-12-13 下午6:51
 * Version: 1.0
 * LastModified: 18-12-5 下午2:29
 */

package com.topsun.framework.common.core.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 获取Spring应用上下文环境ApplicationContext
 */
public class ContextUtil implements ApplicationContextAware {
	/**
	 * Spring应用上下文环境
	 */
	private static ApplicationContext applicationContext;

	/**
	 * 实现ApplicationContextAware接口的回调方法，设置上下文环境
	 * @param applicationContext 上下文
	 * @throws BeansException 异常
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ContextUtil.applicationContext = applicationContext;
	}

	/**
	 * @return ApplicationContext 上下文
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 获取bean
	 * @param requiredType 类型
	 * @param <T> 返回Bean
	 * @return
	 */
	public static <T> T getBean(Class<T> requiredType) {
		return getApplicationContext().getBean(requiredType);
	}
}
